<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="规格名称" prop="goodsSpecName">
        <el-input
          v-model="queryParams.goodsSpecName"
          placeholder="请输入规格名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格值" prop="specsValue">
        <el-input
          v-model="queryParams.specsValue"
          placeholder="请输入规格值"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAddSpec"
        >新增规格</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Plus"
          @click="handleAddSpecsValue"
          :disabled="!selectedSpec"
        >新增规格值</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Refresh"
          @click="handleRefresh"
        >刷新列表</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Document"
          @click="handleExport"
        >导出数据</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 树形表格 -->
    <el-table
      v-loading="loading"
      :data="goodspecsTreeList"
      row-key="uniqueKey"
      :tree-props="{ children: 'specsValues', hasChildren: 'hasChildren' }"
      @row-click="handleRowClick"
      @row-contextmenu="handleRowContextMenu"
      highlight-current-row
    >
      <el-table-column label="规格名称" prop="goodsSpecName" min-width="200">
        <template #default="scope">
          <span v-if="scope.row.goodsSpecName" :style="{ fontWeight: 'bold', color: '#409EFF' }">
            {{ scope.row.goodsSpecName }}
            <el-tag v-if="scope.row.specsValues && scope.row.specsValues.length > 0" 
                    size="small" 
                    type="info" 
                    style="margin-left: 8px;">
              {{ scope.row.specsValues.length }}个规格值
            </el-tag>
          </span>
          <span v-else-if="scope.row.specsValue" :style="{ paddingLeft: '20px' }">
            {{ scope.row.specsValue }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="所属规格" align="center" width="120">
        <template #default="scope">
          <span v-if="scope.row.specsValue" style="color: #909399; font-size: 12px;">
            {{ getSpecNameById(scope.row.goodsSpecsId) }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.goodsSpecName" type="primary">规格</el-tag>
          <el-tag v-else-if="scope.row.specsValue" type="success">规格值</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="商家ID" align="center" prop="businessId" width="100" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280">
        <template #default="scope">
          <!-- 规格行的操作按钮 -->
          <el-button 
            v-if="scope.row.goodsSpecName"
            link 
            type="primary" 
            icon="Edit" 
            @click="handleUpdateSpec(scope.row)" 
          >修改规格</el-button>
          <el-button 
            v-if="scope.row.goodsSpecName"
            link 
            type="success" 
            icon="Plus" 
            @click="handleAddSpecsValueForSpec(scope.row)" 
          >添加规格值</el-button>
          <el-button 
            v-if="scope.row.goodsSpecName"
            link 
            type="danger" 
            icon="Delete" 
            @click="handleDeleteSpec(scope.row)" 
          >删除规格</el-button>
          
          <!-- 规格值行的操作按钮 -->
          <el-button 
            v-if="scope.row.specsValue"
            link 
            type="primary" 
            icon="Edit" 
            @click="handleUpdateSpecsValue(scope.row)" 
          >修改规格值</el-button>
          <el-button 
            v-if="scope.row.specsValue"
            link 
            type="danger" 
            icon="Delete" 
            @click="handleDeleteSpecsValue(scope.row)" 
          >删除规格值</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改商品规格对话框 -->
    <el-dialog :title="specTitle" v-model="specOpen" width="500px" append-to-body>
      <el-form ref="specFormRef" :model="specForm" :rules="specRules" label-width="80px">
        <el-form-item label="规格名称" prop="goodsSpecName">
          <el-input v-model="specForm.goodsSpecName" placeholder="请输入规格名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSpecForm">确 定</el-button>
          <el-button @click="cancelSpec">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改规格值对话框 -->
    <el-dialog :title="specsValueTitle" v-model="specsValueOpen" width="500px" append-to-body>
      <el-form ref="specsValueFormRef" :model="specsValueForm" :rules="specsValueRules" label-width="80px">
        <el-form-item label="规格值" prop="specsValue">
          <el-input v-model="specsValueForm.specsValue" placeholder="请输入规格值" />
        </el-form-item>
        <el-form-item label="所属规格" prop="goodsSpecsId">
          <el-select 
            v-model="specsValueForm.goodsSpecsId" 
            placeholder="请选择所属规格" 
            style="width: 100%"
            :disabled="specsValueForm.id || specsValueForm.goodsSpecsId"
          >
            <el-option 
              v-for="spec in specsList" 
              :key="spec.goodsSpecId" 
              :label="spec.goodsSpecName" 
              :value="spec.goodsSpecId" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSpecsValueForm">确 定</el-button>
          <el-button @click="cancelSpecsValue">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Goodspecs">
import { listGoodspecs, getGoodspecs, delGoodspecs, addGoodspecs, updateGoodspecs, getGoodspecsTree } from "@/api/lkshop/goodspecs"
import { listSpecs, getSpecs, delSpecs, addSpecs, updateSpecs } from "@/api/lkshop/specs"
import useUserStore from "@/store/modules/user"

const { proxy } = getCurrentInstance()
const userStore = useUserStore()

const goodspecsTreeList = ref([])
const specsList = ref([])
const selectedSpec = ref(null)
const loading = ref(true)
const showSearch = ref(true)

// 规格相关
const specOpen = ref(false)
const specTitle = ref("")
const specForm = ref({})
const specRules = {
  goodsSpecName: [
    { required: true, message: "规格名称不能为空", trigger: "blur" }
  ]
}

// 规格值相关
const specsValueOpen = ref(false)
const specsValueTitle = ref("")
const specsValueForm = ref({})
const specsValueRules = {
  specsValue: [
    { required: true, message: "规格值不能为空", trigger: "blur" }
  ],
  goodsSpecsId: [
    { required: true, message: "请选择所属规格", trigger: "change" }
  ]
}

const data = reactive({
  queryParams: {
    goodsSpecName: null,
    specsValue: null
  }
})

const { queryParams } = toRefs(data)

/** 查询商品规格树形列表 */
function getList() {
  loading.value = true
  
  // 使用用户存储中的商家ID
  const businessId = userStore.businessId
  console.log('=== 商品规格页面获取商家ID ===')
  console.log('用户存储中的商家ID:', businessId)
  
  if (!businessId) {
    console.warn('未找到商家ID，无法获取商品规格列表')
    proxy.$modal.msgWarning("未找到商家信息，请重新登录")
    loading.value = false
    return
  }
  
  // 构建查询参数
  const params = { businessId: businessId }
  if (queryParams.value.goodsSpecName) {
    params.goodsSpecName = queryParams.value.goodsSpecName
  }
  if (queryParams.value.specsValue) {
    params.specsValue = queryParams.value.specsValue
  }
  
  getGoodspecsTree(params).then(response => {
    console.log('商品规格树形数据:', response.data)
    goodspecsTreeList.value = response.data || []
    loading.value = false
  }).catch(error => {
    console.error('获取商品规格树形数据失败:', error)
    goodspecsTreeList.value = []
    loading.value = false
  })
}

/** 获取规格列表（用于规格值选择） */
function getSpecsList() {
  const businessId = userStore.businessId
  if (!businessId) return
  
  listGoodspecs({ businessId: businessId }).then(response => {
    specsList.value = response.rows || []
  }).catch(error => {
    console.error('获取规格列表失败:', error)
    specsList.value = []
  })
}

/** 根据规格ID获取规格名称 */
function getSpecNameById(specId) {
  const spec = specsList.value.find(item => item.goodsSpecId === specId)
  return spec ? spec.goodsSpecName : '未知规格'
}

/** 处理行点击 */
function handleRowClick(row) {
  if (row.goodsSpecName) {
    // 点击的是规格行
    selectedSpec.value = row
  }
}

/** 处理行右键菜单 */
function handleRowContextMenu(event, row) {
  if (row.goodsSpecName) {
    // 右键点击的是规格行
    selectedSpec.value = row
    proxy.$emit('openContextMenu', event, row)
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 刷新按钮操作 */
function handleRefresh() {
  getList()
  getSpecsList()
}

/** 导出按钮操作 */
function handleExport() {
  const businessId = userStore.businessId
  if (!businessId) {
    proxy.$modal.msgWarning("未找到商家信息，无法导出数据")
    return
  }
  
  proxy.download('lkshop/goodspecs/export', {
    businessId: businessId,
    goodsSpecName: queryParams.value.goodsSpecName,
    specsValue: queryParams.value.specsValue
  }, `商品规格数据_${new Date().getTime()}.xlsx`)
}

// 规格相关操作
/** 新增规格按钮操作 */
function handleAddSpec() {
  resetSpecForm()
  specOpen.value = true
  specTitle.value = "添加商品规格"
}

/** 修改规格按钮操作 */
function handleUpdateSpec(row) {
  resetSpecForm()
  const goodsSpecId = row.goodsSpecId
  getGoodspecs(goodsSpecId).then(response => {
    specForm.value = response.data
    specOpen.value = true
    specTitle.value = "修改商品规格"
  })
}

/** 删除规格按钮操作 */
function handleDeleteSpec(row) {
  // 检查是否有关联的规格值
  if (row.specsValues && row.specsValues.length > 0) {
    proxy.$modal.confirm(
      `规格"${row.goodsSpecName}"下还有${row.specsValues.length}个规格值，删除规格将同时删除所有关联的规格值，是否继续？`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      performDeleteSpec(row.goodsSpecId, row.goodsSpecName)
    }).catch(() => {})
  } else {
    performDeleteSpec(row.goodsSpecId, row.goodsSpecName)
  }
}

/** 执行删除规格操作 */
function performDeleteSpec(goodsSpecId, goodsSpecName) {
  proxy.$modal.confirm('是否确认删除商品规格"' + goodsSpecName + '"？').then(function() {
    return delGoodspecs(goodsSpecId)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

// 规格值相关操作
/** 新增规格值按钮操作 */
function handleAddSpecsValue() {
  if (!selectedSpec.value) {
    proxy.$modal.msgWarning("请先选择一个规格")
    return
  }
  resetSpecsValueForm()
  specsValueForm.value.goodsSpecsId = selectedSpec.value.goodsSpecId
  specsValueForm.value.businessId = userStore.businessId
  specsValueOpen.value = true
  specsValueTitle.value = "添加规格值 - " + selectedSpec.value.goodsSpecName
}

/** 为指定规格添加规格值按钮操作 */
function handleAddSpecsValueForSpec(row) {
  console.log('=== 为指定规格添加规格值 ===')
  console.log('规格行数据:', row)
  console.log('商家ID:', userStore.businessId)
  
  resetSpecsValueForm()
  specsValueForm.value.goodsSpecsId = row.goodsSpecId
  specsValueForm.value.businessId = userStore.businessId
  
  console.log('规格值表单数据:', specsValueForm.value)
  
  specsValueOpen.value = true
  specsValueTitle.value = "添加规格值 - " + row.goodsSpecName
}

/** 修改规格值按钮操作 */
function handleUpdateSpecsValue(row) {
  resetSpecsValueForm()
  const id = row.id
  getSpecs(id).then(response => {
    specsValueForm.value = response.data
    specsValueOpen.value = true
    specsValueTitle.value = "修改规格值"
  })
}

/** 删除规格值按钮操作 */
function handleDeleteSpecsValue(row) {
  const id = row.id
  proxy.$modal.confirm('是否确认删除规格值"' + row.specsValue + '"？').then(function() {
    return delSpecs(id)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

// 表单操作
/** 规格表单重置 */
function resetSpecForm() {
  specForm.value = {
    goodsSpecId: null,
    goodsSpecName: null,
    businessId: userStore.businessId
  }
  proxy.resetForm("specFormRef")
}

/** 规格值表单重置 */
function resetSpecsValueForm() {
  specsValueForm.value = {
    id: null,
    specsValue: null,
    goodsSpecsId: null,
    businessId: userStore.businessId
  }
  proxy.resetForm("specsValueFormRef")
}

/** 规格表单取消 */
function cancelSpec() {
  specOpen.value = false
  resetSpecForm()
}

/** 规格值表单取消 */
function cancelSpecsValue() {
  specsValueOpen.value = false
  resetSpecsValueForm()
}

/** 规格表单提交 */
function submitSpecForm() {
  proxy.$refs["specFormRef"].validate(valid => {
    if (valid) {
      if (specForm.value.goodsSpecId != null) {
        updateGoodspecs(specForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          specOpen.value = false
          getList()
        })
      } else {
        addGoodspecs(specForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          specOpen.value = false
          getList()
          getSpecsList()
        })
      }
    }
  })
}

/** 规格值表单提交 */
function submitSpecsValueForm() {
  proxy.$refs["specsValueFormRef"].validate(valid => {
    if (valid) {
      if (specsValueForm.value.id != null) {
        updateSpecs(specsValueForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          specsValueOpen.value = false
          getList()
        })
      } else {
        addSpecs(specsValueForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          specsValueOpen.value = false
          getList()
        })
      }
    }
  })
}

// 初始化
getList()
getSpecsList()
</script>
